from typing import Any, Awaitable, Callable, Dict

from aiogram import BaseMiddleware
from aiogram.types import TelegramObject
from sqlalchemy.ext.asyncio import async_sessionmaker

# from src.database.services.delivery_zone import DeliveryZoneService
# from src.database.services.discount import DiscountService
# from src.database.services.order import OrderService
# from src.database.services.payment_method import PaymentMethodService
# from src.database.services.product import ProductService
# from src.database.services.promocode import PromocodeService
# from src.database.services.shop import ShopService
# from src.database.services.statistics import StatsService
# from src.database.services.ticket import TicketService
import src.database.services as services
from src.database.uow.uow import build_uow


class DBSessionMiddleware(BaseMiddleware):
    def __init__(self, sessionmaker: async_sessionmaker) -> None:
        self.sessionmaker = sessionmaker

    async def __call__(
        self,
        handler: Callable[[TelegramObject, Dict[str, Any]], Awaitable[Any]],
        event: TelegramObject,
        data: Dict[str, Any],
    ) -> Any:
        async with self.sessionmaker() as session:
            uow = build_uow(session)
            data["uow"] = uow
            data["user_service"] = services.UserService(uow)
            data["subscription_service"] = services.SubscriptionService(uow)
            data["bot_settings_service"] = services.BotSettingsService(uow)
            data["codes_service"] = services.ActivationCodeService(uow)
            data["category_service"] = services.CategoryService(uow)
            data["calendar_service"] = services.CalendarService(uow)
            data["bill_service"] = services.BillService(uow)

            result = await handler(event, data)
            return result
